﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Web;

namespace OpenQuarters.EntityBase
{
    public static class DataContextHelper
    {
        public static Dictionary<string, Type> Helpers
        {
            get
            {
                DebugHelper.Write("Helpers get");
                if (HttpContext.Current.Session["__DataContextHelper_RegisteredHelpers"] == null)
                {
                    DebugHelper.Write("Helpers get, is null");
                    HttpContext.Current.Session["__DataContextHelper_RegisteredHelpers"] = new Dictionary<string, Type>();
                    DataContextHelper.RegisterHelpers();
                }
                return (Dictionary<string, Type>)HttpContext.Current.Session["__DataContextHelper_RegisteredHelpers"];
            }
            set
            {
                DebugHelper.Write("Helpers set");
                HttpContext.Current.Session["__DataContextHelper_RegisteredHelpers"] = value;
            }
        }

        public static void RegisterHelper<TDataContextType, TDataContextHelperType>()
            where TDataContextType : DataContext
            where TDataContextHelperType : IDataContextHelper
        {
            if (Helpers.ContainsKey(typeof(TDataContextType).FullName))
            {
                Helpers.Remove(typeof(TDataContextType).FullName);
            }
            Helpers.Add(typeof(TDataContextType).FullName, typeof(TDataContextHelperType));
        }

        public static T GetDataContext<T>() where T : DataContext
        {
            DebugHelper.Write("GetDataContext<" + typeof(T).FullName + ">");
            if (!Helpers.ContainsKey(typeof(T).FullName))
            {
                DebugHelper.Write("No helper found, creating instance with string '" + Activator.CreateInstance<T>().Connection.ConnectionString + "'");
                return Activator.CreateInstance<T>();
            }
            else
            {
                string connString = ((IDataContextHelper)Activator.CreateInstance(Helpers[typeof(T).FullName])).GetConnectionString<T>();
                DebugHelper.Write("Using connection string '" + connString + "'");
                return (T)typeof(T).GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { connString });
            }
        }

        public static void RegisterHelpers()
        {
            foreach (var t in Utils.GetSubclassesOf(typeof(IDataContextHelper), true))
            {
                DebugHelper.Write("Registering helper for " + t.FullName);
                ((IDataContextHelper)Activator.CreateInstance(t)).RegisterHelpers();
            }
        }
    }
}
